package com.zhiy.com.estation.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by chuyh on 2016/9/29.
 * <p/>
 * 该imagetools工具实现的功能：
 * bitmap、drawable、byte[]三者之间相互转化
 * 将bitmap保存到sdcard
 * 从sdcard取出保存的图片
 */
public class ImageTools {
    /**
     * Transfer drawable to bitmap
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * Transfer drawable to bitmap
     *
     * @param context
     * @param drawableid
     * @return
     */
    public static Bitmap drawableToBitmap(Context context, int drawableid) {
        return BitmapFactory.decodeResource(context.getResources(), drawableid);
    }

    /**
     * Transfer bitmap to drawable
     *
     * @param context
     * @param bitmap
     * @return
     */
    public static Drawable bitmapToDrawable(Context context, Bitmap bitmap) {
        return new BitmapDrawable(context.getResources(), bitmap);
    }

    /**
     * Transfer Input stream to bitmap
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static Bitmap inputStreamToBitmap(InputStream inputStream)
            throws Exception {
        return BitmapFactory.decodeStream(inputStream);
    }


    /**
     * Transfer bitmap to Bytes
     *
     * @param bitmap
     * @return
     */
    public static byte[] bitmapToBytes(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Transfer Bytes to bitmap
     *
     * @param byteArray
     * @return
     */
    public static Bitmap bytesToBitmap(byte[] byteArray) {
        if (byteArray.length != 0) {
            return BitmapFactory
                    .decodeByteArray(byteArray, 0, byteArray.length);
        } else {
            return null;
        }
    }

    /**
     * Transfer Bytes to drawable
     *
     * @param byteArray
     * @return
     */
    public static Drawable bytesToDrawable(byte[] byteArray) {
        ByteArrayInputStream ins = null;
        if (byteArray != null) {
            ins = new ByteArrayInputStream(byteArray);
        }
        return Drawable.createFromStream(ins, null);
    }

    /**
     * Transfer drawable to bytes
     *
     * @param drawable
     * @return
     */
    public static byte[] drawableToBytes(Drawable drawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        Bitmap bitmap = bitmapDrawable.getBitmap();
        return bitmapToBytes(bitmap);
    }

    /**
     * Check the SD card
     *
     * @return
     */
    public static boolean checkSDCardAvailable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * Get images from SD card by path and the name of image
     *
     * @return
     */
//    public static Bitmap getPhotoFromSDCard(String name) {
//        return BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + "/" + name);
//    }

    public static Bitmap getPhotoFromSDCard(String path){
        return BitmapFactory.decodeFile(path);
    }

    /**
     * Save image to the SD card
     *
     * @param photoBitmap
     * @param photoName
     */
    public static File savePhotoToSDCard(Bitmap photoBitmap, String photoName) {
        File photoFile = null;
        String path = Environment.getExternalStorageDirectory().getPath();
        if (checkSDCardAvailable()) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            photoFile = new File(path, photoName);
            FileOutputStream fileOutputStream = null;
            try {
                photoFile.createNewFile();
                fileOutputStream = new FileOutputStream(photoFile);
                Log.d("--", "开始保存文件 -- " + path + "/" + photoName);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
                        fileOutputStream.flush();
                        Log.d("--", "保存文件成功");
                    }
                }
            } catch (Exception e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return photoFile;
    }
    public static String savePhotoToSDCardPath(Bitmap photoBitmap,String photoName){
        String path= Environment.getExternalStorageDirectory().getPath();
        File photoFile=null;
        if (checkSDCardAvailable()) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            photoFile = new File(path, photoName + ".png");
            FileOutputStream fileOutputStream = null;
            Log.d("--", "开始保存文件--" + path + "/" + photoName + ".png");
            try {
                photoFile.createNewFile();
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) ;
                    {
                        fileOutputStream.flush();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    if (fileOutputStream!=null){
                        fileOutputStream.close();
                    }
                }
                catch (IOException e){
                    e.printStackTrace();
                }
            }

        }
        return path + "/" + photoName+".png";
    }

}
